<template>
  <div>
    <el-form-item :prop="item.name || ''" :label="item.label" v-bind="item.formItemProps || {}" ref="el-form-item">
      <el-row type="flex" justify="space-between" :style="contentStyle">
        <div class="flexitem">
          <el-input ref="input" type="text" v-model="mvalue" v-bind="opt" @keyup.enter.native="eventTrigger( 'onEnter', $event)"></el-input>
        </div>
        <div class>
          <el-button
            :style="sendbuttonStyle"
            :type="sendbuttonType"
            :disabled="sendbuttonDisabled"
            :loading="sendbuttonLoading"
            @click="sendCode"
          >{{sendbuttonText}}</el-button>
        </div>
      </el-row>
    </el-form-item>
  </div>
</template>

<script>
  import { objectAssign } from "../../utils/common";
  import { server_request } from "../../utils/request";
  import StrAllMixin from "../validMixins/StrAllMixin";
  import Required from "../validMixins/Required";
  import NumberAllMixin from "../validMixins/NumberAllMixin";
  import EventTrigger from "../plugsMixins/EventTrigger";
  import baseConfig from "../../config/base";

  var defaultCaptchaStyle = { width: "120px", height: "40px", marginLeft: "5px" };
  var defaultContentStyle = { width: "100%" };

  /**
   * 发送（手机）验证码
   *
   */
  export default {
    name: "PopoSendcode",
    props: {
      value: { type: String },
      item: { type: Object },
      formData: { type: Object },
    },
    mixins: [EventTrigger, StrAllMixin, Required, NumberAllMixin],
    data() {
      return {
        mvalue: this.value,
        codeUrl: "",
        paramFn: null, // 用于获取发送到codeUrl中的参数的函数
        sendbuttonStyle: defaultCaptchaStyle,
        contentStyle: defaultContentStyle,
        sendbuttonType: "primary",
        sendbuttonDisabled: false,
        sendbuttonLoading: false,
        sendbuttonText: "发送验证码",
        sendbuttonDefaultText: "发送验证码", // 默认情况下（ready情况）的按钮文字
        sendbuttonSuccessText: "验证码已发送", // 发送成功后的提示性文字，1s后会转为倒计时
        key: window.location.href, // 当前发送按钮的关键字，不同关键字不会共享发送控制逻辑
        timeout: 60, // 发送时间间隔，单位秒
        _currentNumber: 0, // 倒计时计数字段
        opt: {},
      };
    },
    watch: {
      mvalue(val) {
        this.$emit("input", val);
      },
    },
    created() {
      this.key = window.btoa(window.location.href).substr(0, 10);
      this.key = this.item.key !== undefined ? this.item.key : this.key;
      this.key = "sendcode_" + this.key;
      this.sendbuttonDefaultText =
        this.item.sendbuttonDefaultText !== undefined ? this.item.sendbuttonDefaultText : this.sendbuttonDefaultText;
      this.sendbuttonSuccessText =
        this.item.sendbuttonSuccessText !== undefined ? this.item.sendbuttonSuccessText : this.sendbuttonSuccessText;
      this.sendbuttonText =
        this.item.sendbuttonDefaultText !== undefined ? this.item.sendbuttonDefaultText : this.sendbuttonDefaultText;
      this.paramFn = this.item.paramFn !== undefined ? this.item.paramFn : null;
      this.timeout = this.item.timeout !== undefined ? this.item.timeout : this.timeout;
      let codeUrl = this.item.codeUrl;
      if( codeUrl.substr(0,1) == "@"){
        codeUrl = baseConfig.server_root + codeUrl.substr( 1);
      }
      this.codeUrl = codeUrl;

      var opt = objectAssign({}, this.item.props);
      this.sendbuttonStyle = objectAssign(
        {},
        defaultCaptchaStyle,
        {
          width: this.item.captchaWidth !== undefined ? this.item.captchaWidth : this.sendbuttonStyle.width,
          height: this.item.captchaHeight !== undefined ? this.item.captchaHeight : this.sendbuttonStyle.height,
        },
        this.item.captchaStyle
      );

      this.contentStyle = objectAssign(
        {},
        defaultContentStyle,
        {
          width: this.item.contentWidth !== undefined ? this.item.contentWidth : this.contentStyle.width,
        },
        this.item.contentStyle
      );

      this.opt = opt;
    },
    mounted() {
      this.$nextTick(() => {
        this.initButtonStatus();
      });
    },
    methods: {
      timestamp() {
        return parseInt(Date.now() / 1000);
      },
      initButtonStatus() {
        var disabled = false;
        var lastSeconds = localStorage[this.key + "_lastsec"];
        if (lastSeconds != null) {
          var surplus_sec = this.timestamp() - parseInt(lastSeconds);
          disabled = surplus_sec < this.timeout;
          if (disabled) {
            this._currentNumber = this.timeout - surplus_sec;
            this.secDownTimeout();
          }
        }

        this.sendbuttonDisabled = disabled;
      },

      startSecDown() {
        var secs = this.timestamp();
        localStorage[this.key + "_lastsec"] = secs;
        this.sendbuttonText = this.sendbuttonSuccessText;
        this.sendbuttonDisabled = true;
        this.sendbuttonLoading = false;
        this._currentNumber = this.timeout;
        this.secDownTimeout();
      },

      /**
       * 倒计时功能
       */
      secDown() {
        if (this._currentNumber <= 0) {
          this.sendbuttonText = this.sendbuttonDefaultText;
          this.sendbuttonDisabled = false;
          return;
        }
        this.sendbuttonText = this._currentNumber + "s";
        localStorage[this.key + "_currentsec"] = this._currentNumber;
        this._currentNumber--;
        this.secDownTimeout();
      },
      secDownTimeout() {
        window.setTimeout(() => {
          this.secDown();
        }, 1000);
      },
      sendCode() {
        var obj = {
          code: 100,
          message: "发送失败，请示参数为空",
          data: {},
        };

        if (!this.codeUrl) {
          obj.message = "发送失败，请示接口为空";
        } else {
          if (this.paramFn != null) {
            obj = this.paramFn();
          }
        }

        if (!obj) {
          return;
        }
        if (obj.code != 200) {
          this.$message.error(obj.message);
          return;
        }

        this.sendbuttonLoading = true;
        server_request(this.codeUrl, obj.data)
          .then((res) => {
            if (res.code == 200) {
              this.sendbuttonLoading = false;
              this.$message.success("发送成功");
              this.startSecDown();
            }else{
              this.sendbuttonLoading = false;
              console.error("发送验证码失败", res);
              this.$message.error("发送失败");
            }
          })
          .catch((e) => {
            this.sendbuttonLoading = false;
            console.error("发送验证码失败", e);
            this.$message.error("发送失败");
          });
      },
    },
  };
</script>


<style scoped lang="scss">
::v-deep {
  .el-avatar > img {
    width: 100%;
    height: 100%;
  }

  .image-slot {
    text-align: center;
    font-size: 20px;
    color: #ccc;
  }
  .image-loading-slot {
    text-align: center;
    font-size: 12px;
    color: #ccc;
  }
}
.flexitem {
  flex: 10;
}
</style>
